package com.llmcu.source.javase.thread.threadlocal;

import java.util.concurrent.TimeUnit;

/**
 * 不用static修饰ThreadLocal对象
 *
 * @author liuling
 * @date 2024/11/28 19:23
 */
public class NonStaticThreadLocalDemo {
    private ThreadLocal<String> threadLocal = new ThreadLocal<>();
    public static void main(String[] args) {
        NonStaticThreadLocalDemo demo = new NonStaticThreadLocalDemo();
        new Thread(()->{
            demo.threadLocal.set("A");
            System.out.println(Thread.currentThread().getId()+"-set:A");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getId()+"-get:"+demo.threadLocal.get());
            demo.threadLocal.remove();
        }).start();
        new Thread(()->{
            demo.threadLocal.set("B");
            System.out.println(Thread.currentThread().getId()+"-set:B");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getId()+"-get:"+demo.threadLocal.get());
            demo.threadLocal.remove();
        }).start();
    }
}
